<template>
  <div class="classroom-container">
    <h2>Tutoring Classroom</h2>
    <div class="classroom-controls">
      <button @click="toggleRecording" class="control-btn">{{ isRecording ? 'Stop Recording' : 'Start Recording' }}</button>
      <button @click="shareScreen" class="control-btn">Share Screen</button>
      <button @click="endSession" class="control-btn danger">End Session</button>
    </div>
    <div class="classroom-layout">
      <div class="video-section">
        <div class="teacher-video">
          <video id="teacher-video" ref="teacherVideo" autoplay playsinline></video>
          <p>Teacher</p>
        </div>
        <div class="student-video">
          <video id="student-video" ref="studentVideo" autoplay playsinline></video>
          <p>Student</p>
        </div>
      </div>
      <div class="chat-section">
        <div class="chat-messages" ref="chatContainer">
          <div v-for="(msg, index) in messages" :key="index" class="message">
            <strong>{{ msg.sender }}:</strong> {{ msg.text }}
          </div>
        </div>
        <div class="chat-input">
          <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type your message..." />
          <button @click="sendMessage">Send</button>
        </div>
      </div>
    </div>
    <div class="classroom-timer">
      Time remaining: {{ formattedTimeRemaining }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'

export default {
  name: 'ClassroomComponent',
  setup() {
    const route = useRoute()
    const teacherVideo = ref(null)
    const studentVideo = ref(null)
    const chatContainer = ref(null)
    const newMessage = ref('')
    const messages = ref([])
    const isRecording = ref(false)
    const timeRemaining = ref(0) // in seconds
    const timerInterval = ref(null)
    
    // WebRTC related
    const peerConnection = ref(null)
    const localStream = ref(null)
    
    onMounted(async () => {
      // Initialize the classroom
      await initializeClassroom()
      
      // Start the session timer
      startTimer()
    })
    
    onUnmounted(() => {
      // Cleanup
      if (timerInterval.value) clearInterval(timerInterval.value)
      if (peerConnection.value) peerConnection.value.close()
      if (localStream.value) localStream.value.getTracks().forEach(track => track.stop())
    })
    
    const initializeClassroom = async () => {
      // Get session ID from route params
      const sessionId = route.params.sessionId
      
      try {
        // Fetch classroom details
        const response = await fetch(`/api/classrooms/${sessionId}`, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (!response.ok) {
          throw new Error('Failed to get classroom')
        }
        
        const data = await response.json()
        console.log('Classroom data:', data)
        
        // Initialize WebRTC connection
        await initWebRTC(data.webrtcConfig)
        
        // Join the chat room for this session
        joinChatRoom(sessionId)
      } catch (error) {
        console.error('Failed to initialize classroom:', error)
      }
    }
    
    const initWebRTC = async (config) => {
      // Create RTCPeerConnection
      const configuration = {
        iceServers: config.iceServers
      }
      
      peerConnection.value = new RTCPeerConnection(configuration)
      
      // Handle incoming tracks
      peerConnection.value.addEventListener('track', event => {
        if (event.track.kind === 'video') {
          if (studentVideo.value) {
            studentVideo.value.srcObject = event.streams[0]
          }
        } else if (event.track.kind === 'audio') {
          // Audio tracks are typically part of the same stream
          if (studentVideo.value && !studentVideo.value.srcObject) {
            studentVideo.value.srcObject = event.streams[0]
          }
        }
      })
      
      // Get local media
      try {
        localStream.value = await navigator.mediaDevices.getUserMedia({ 
          video: true, 
          audio: true 
        })
        
        if (teacherVideo.value) {
          teacherVideo.value.srcObject = localStream.value
        }
        
        // Add tracks to peer connection
        localStream.value.getTracks().forEach(track => {
          peerConnection.value.addTrack(track, localStream.value)
        })
      } catch (error) {
        console.error('Error accessing media devices:', error)
      }
    }
    
    const joinChatRoom = (sessionId) => {
      // Join a WebSocket chat room for this session
      // In a real implementation, this would connect to a WebSocket endpoint
      // Placeholder implementation:
      console.log(`Joined chat room for session: ${sessionId}`)
    }
    
    const sendMessage = () => {
      if (newMessage.value.trim() === '') return
      
      // Send message via WebSocket or HTTP
      const messageObj = {
        sender: 'You',
        text: newMessage.value,
        timestamp: new Date()
      }
      
      messages.value.push(messageObj)
      newMessage.value = ''
      
      // Scroll to bottom of chat
      if (chatContainer.value) {
        chatContainer.value.scrollTop = chatContainer.value.scrollHeight
      }
    }
    
    const startTimer = () => {
      // Get session duration from props or API
      // For now, using a default of 60 minutes (3600 seconds)
      timeRemaining.value = 3600 // 60 minutes in seconds
      
      timerInterval.value = setInterval(() => {
        if (timeRemaining.value > 0) {
          timeRemaining.value--
        } else {
          clearInterval(timerInterval.value)
          // Session ended
          alert('Session has ended.')
        }
      }, 1000)
    }
    
    const toggleRecording = () => {
      isRecording.value = !isRecording.value
      // In a real implementation, this would send a command to the backend
      console.log(isRecording.value ? 'Started recording' : 'Stopped recording')
    }
    
    const shareScreen = async () => {
      try {
        // Get screen stream
        const screenStream = await navigator.mediaDevices.getDisplayMedia({ 
          video: true 
        })
        
        // Replace the current video track with the screen capture
        const videoTrack = screenStream.getVideoTracks()[0]
        const sender = peerConnection.value.getSenders().find(sender => 
          sender.track && sender.track.kind === 'video'
        )
        
        if (sender) {
          sender.replaceTrack(videoTrack)
        }
        
        // Listen for when the user stops sharing
        screenStream.getVideoTracks()[0].onended = () => {
          // Switch back to camera
          if (localStream.value) {
            const cameraTrack = localStream.value.getVideoTracks()[0]
            if (sender) {
              sender.replaceTrack(cameraTrack)
            }
          }
        }
      } catch (error) {
        console.error('Error sharing screen:', error)
      }
    }
    
    const endSession = () => {
      // In a real implementation, this would send a request to end the session
      alert('Session ended')
      // Possibly navigate away from classroom page
    }
    
    // Computed property for formatted time remaining
    const formattedTimeRemaining = () => {
      const hours = Math.floor(timeRemaining.value / 3600)
      const minutes = Math.floor((timeRemaining.value % 3600) / 60)
      const seconds = timeRemaining.value % 60
      
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    }
    
    return {
      teacherVideo,
      studentVideo,
      chatContainer,
      newMessage,
      messages,
      isRecording,
      timeRemaining,
      formattedTimeRemaining,
      sendMessage,
      toggleRecording,
      shareScreen,
      endSession
    }
  }
}
</script>

<style scoped>
.classroom-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.classroom-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  justify-content: center;
}

.control-btn {
  padding: 8px 16px;
  border: 1px solid #ccc;
  background-color: #f0f0f0;
  cursor: pointer;
  border-radius: 4px;
}

.control-btn:hover {
  background-color: #e0e0e0;
}

.control-btn.danger {
  background-color: #f8d7da;
  border-color: #f5c6cb;
  color: #721c24;
}

.classroom-layout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.video-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.teacher-video, .student-video {
  text-align: center;
}

.teacher-video video, .student-video video {
  width: 100%;
  max-height: 300px;
  background-color: #000;
  border-radius: 4px;
}

.chat-section {
  display: flex;
  flex-direction: column;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.chat-messages {
  flex-grow: 1;
  height: 300px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 10px;
  padding: 5px;
  background-color: #fff;
  border-radius: 4px;
  text-align: left;
}

.chat-input {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
}

.chat-input input {
  flex-grow: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px 0 0 4px;
}

.chat-input button {
  padding: 8px 15px;
  border: 1px solid #ccc;
  border-left: none;
  border-radius: 0 4px 4px 0;
  background-color: #007bff;
  color: white;
  cursor: pointer;
}

.classroom-timer {
  text-align: center;
  font-size: 1.2em;
  font-weight: bold;
  margin-top: 20px;
  padding: 10px;
  background-color: #e9ecef;
  border-radius: 4px;
}
</style>